package com.flashcash.kotlin.fragment

import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.ImageButton
import android.widget.TextView
import android.widget.Toast
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.bigkoo.pickerview.view.OptionsPickerView
import com.bumptech.glide.Glide
import com.flashcash.kotlin.data.FileType
import com.flashcash.kotlin.fragment.certfication.DataObserable
import com.flashcash.kotlin.utils.FirebaseAnalyticsConstants
import com.flashcash.kotlin.utils.FirebaseAnalyticsUtils
import com.flashcash.kotlin.utils.adjustImg
import com.flashcash.kotlin.widget.LocalButton
import com.flashcash.solu.R
import com.flashcash.solu.app.base.BaseFragment
import com.flashcash.solu.app.base.presenter.BaseFragmentPresenter
import com.flashcash.solu.app.base.presenter.BaseFragmentPresenterImpl
import com.flashcash.solu.bean.*
import com.flashcash.solu.common.EventCollection
import com.flashcash.solu.common.FieldParams
import com.flashcash.solu.common.FieldParamsInt
import com.flashcash.solu.common.TokenManager
import com.flashcash.solu.common.adapter.InfoAdapter
import com.flashcash.solu.common.adapter.InfoAdapterEnum
import com.flashcash.solu.common.network.FileUploadUtil
import com.flashcash.solu.utils.ACache
import com.flashcash.solu.utils.DensityUtils
import com.flashcash.solu.view.IntroduceActivity
import com.flashcash.solu.view.MainActivity
import com.flashcash.solu.view.camera.TakePhotoActivity
import com.flashcash.solu.view.certification.ExampleActivity
import com.flashcash.solu.view.certification.ProfessionalInfoActivity
import com.flashcash.solu.view.certification.status.InfoType
import com.flashcash.solu.view.certification.status.JobStatus
import com.flashcash.solu.view.certification.status.RegionLevel
import com.flashcash.solu.view.certification.status.SalaryStatus
import com.flashcash.solu.widget.MyEditTextView
import com.flashcash.solu.widget.SelectView
import com.flashcash.solu.widget.selfdefdialog.DialogManager
import com.flashcash.solu.widget.stepview.HorizontalStepView
import com.flashcash.solu.widget.stepview.bean.StepBean
import com.flashcash.solu.widget.xleotoast.XLeoToast
import com.google.gson.Gson
import com.hwangjr.rxbus.RxBus
import com.jakewharton.rxbinding.widget.RxTextView
import com.x.leo.apphelper.data.cache.CacheDataManage
import com.x.leo.apphelper.log.XLog
import com.x.leo.timelineview.TimeLineView
import okhttp3.ResponseBody
import org.jetbrains.anko.find
import org.jetbrains.anko.sdk25.coroutines.onClick
import retrofit2.Call
import retrofit2.Response
import retrofit2.adapter.rxjava.HttpException
import rx.Observable
import rx.Subscriber
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.io.File
import java.io.FileInputStream
import java.util.*

/**
 * @作者:XLEO
 * @创建日期: 2017/8/15 10:01
 * @描述:${TODO}
 *
 * @更新者:${Author}$
 * @更新时间:${Date}$
 * @更新描述:${TODO}
 * @下一步：
 */
class ProfessionalInfoFragment : BaseFragment<ProfessionalInfoPresenter>(), ProfessionalInfoView {

    override fun finish(): Boolean {
        return !notFinish
    }

    companion object {
        private const val SAVE_INSTANCE_IS_EDITABLE = "save_instance_is_editable"
        const val EXAMPLE_REQUEST_CODE = 700
    }

    private lateinit var jobType: SelectView
    private lateinit var salary: SelectView
    private lateinit var companyName: MyEditTextView
    private lateinit var companyAddress: MyEditTextView
    private lateinit var companyTel: MyEditTextView
    private lateinit var jobInfoSubmitButton: LocalButton
    //    private lateinit var mbdlv: XLeoDropListView
    private lateinit var region: SelectView
    private lateinit var dialogPlus: Dialog
    private var employmentBean: EmploymentBean = EmploymentBean()
    private lateinit var example: TextView
    private lateinit var workImg: ImageButton
    //新增加的字段
    private lateinit var companyAge: SelectView//司龄
    private lateinit var salaryDate: SelectView//发薪日
    private lateinit var convenientTime: SelectView//

//    private var mTelPreStrings: Array<String> = arrayOf("021", "0251")
//    private var mAdapter: DrapListViewAdapter? = null

    private var isEditable: Boolean = false

    private lateinit var ageOP: OptionsPickerView<String>
    private lateinit var salaryDateOP: OptionsPickerView<String>
    private val ageItem = ArrayList<String>()
    private val salaryDateItem = ArrayList<String>()

    override fun doPreBuildHeader(): Boolean {
        return true
    }

    override fun initHeader(view: TextView?): Boolean {
        view!!.text = getString(R.string.textview_field_professional_info)
        return true
    }

    override fun showMessageIcon(): Boolean {
        return false
    }

    override fun getBackPressListener(): View.OnClickListener {
        return View.OnClickListener {
            if (fromSplash) {
                startActivity(Intent(baseActivity, IntroduceActivity::class.java))
            }
            mActivity.finish()
        }
    }

    override fun initPresenter(): ProfessionalInfoPresenter {
        return ProfessionalInfoPresenterImpl()
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_professional_info
    }

    private var hasSave: Boolean = false

    override fun initView(view: View?, savedInstanceState: Bundle?) {
        FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.EXPOSURE_EMPLOY_INFO, null)
        isEditable = CacheDataManage.obtainData(FieldParamsInt.INFO_EDITABLE, Boolean::class.java)
                ?: false
        savedInstanceState?.apply {
            isEditable = get(SAVE_INSTANCE_IS_EDITABLE) as Boolean? ?: false
            if (isEditable) {
                CacheDataManage.addData(FieldParamsInt.INFO_EDITABLE, isEditable)
            }
        }
        if (!isEditable) {
            AlertDialog.Builder(context)
                    .setTitle(R.string.tips_title)
                    .setMessage(R.string.cannot_edit_now)
                    .setPositiveButton(R.string.button_ok, { dialog, _ ->
                        dialog.dismiss()
                    })
                    .create()
                    .show()
        }
        view!!.find<TextView>(R.id.tv_professional).isSelected = true
        view.find<TimeLineView>(R.id.job_node).currentStatus = TimeLineView.ACTIVE
        findAndInit(view)
        jobType.requestFocus()
//        initWorkTelPre()
        editTextChangeEvent()
        if (hasSave && savedInstanceState != null) {
            initViewBySavedState(savedInstanceState)
        }
        updateButtonState()
    }


    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putCharSequence(FieldParams.ProfessionInfo.JOBTYPE, jobType.text)
        outState.putCharSequence(FieldParams.ProfessionInfo.SALARY, salary.text)
        outState.putCharSequence(FieldParams.ProfessionInfo.COMPANYNAME, companyName.text?.toString())
        outState.putCharSequence(FieldParams.ProfessionInfo.COMPANYADDRESS, companyAddress.text?.toString())
        outState.putCharSequence(FieldParams.ProfessionInfo.COMPANYTEL, companyTel.text?.toString())
        outState.putCharSequence(FieldParams.ProfessionInfo.COMPANYAGE, companyAge.text?.toString())
        outState.putCharSequence(FieldParams.ProfessionInfo.SALARYDATE, salaryDate.text?.toString())
        outState.putCharSequence(FieldParams.ProfessionInfo.CONVENIENTTIME, convenientTime.text?.toString())
//        outState.putCharSequence(FieldParams.ProfessionInfo.COMPANYTELPRE, mbdlv.selectedItem)
        outState.putCharSequence(FieldParams.ProfessionInfo.REGION, region.text)
        outState.putBoolean(SAVE_INSTANCE_IS_EDITABLE, isEditable)
        hasSave = true
    }

    private fun initViewBySavedState(state: Bundle) {
        jobType.text = state[FieldParams.ProfessionInfo.JOBTYPE] as String
        salary.text = state[FieldParams.ProfessionInfo.SALARY] as String
        companyName.text = state[FieldParams.ProfessionInfo.COMPANYNAME] as String
        companyTel.text = state[FieldParams.ProfessionInfo.COMPANYTEL] as String
        companyAge.text = state[FieldParams.ProfessionInfo.COMPANYAGE] as String
        salaryDate.text = state[FieldParams.ProfessionInfo.SALARYDATE] as String
        convenientTime.text = state[FieldParams.ProfessionInfo.CONVENIENTTIME] as String
//        val indexOf = mTelPreStrings.indexOf(state[FieldParams.ProfessionInfo.COMPANYTELPRE]?.toString())
//        mbdlv.setSelectedItem(if (indexOf <= -1 || indexOf >= mTelPreStrings.size) {
//            0
//        } else {
//            indexOf
//        })
        region.text = state[FieldParams.ProfessionInfo.REGION] as String
        if (arguments != null) {
            val needUpdate = arguments!![FieldParams.NEED_UPDATE_REGION]
            if (needUpdate != null && needUpdate as Boolean) {
                updateRegion()
                arguments!!.putBoolean(FieldParams.NEED_UPDATE_REGION, false)
            }
        }
        companyAddress.setText(state[FieldParams.ProfessionInfo.COMPANYADDRESS] as String)
        if (ProfessionalInfoActivity.imageInfo != null) {
            workImg.post {
                imgSet()
            }
        }
    }

    private var startLoadImg: Boolean = false
    var firstEdit: Boolean = true//第一次填写

    override fun onProfessionDataObtain(employmentServerBean: Pair<EmploymentServerBean?, RecordFilesResponse?>) {
        if (employmentServerBean.first != null) {
            firstEdit = false
            employmentBean = EmploymentBean(employmentServerBean.first)
            jobType.text = getString(JobStatus.valueOf(employmentBean.jobType).showString)
            salary.text = getString(SalaryStatus.valueOf(employmentBean.salary).showString)
            companyName.text = employmentBean.companyName
            initRegion()
            val companyPhone = employmentBean.companyPhone
//            for (i in 0 until mTelPreStrings.size) {
//                if (companyPhone.startsWith(mTelPreStrings[i])) {
//                    mbdlv.setSelectedItem(i)
//                    companyPhone = companyPhone.substring(mTelPreStrings[i].length)
//                    break
//                }
//            }
            companyTel.text = companyPhone

        }
        if (employmentServerBean.second?.files != null && employmentServerBean.second?.files!!.size > 0) {
            startLoadImg = true
            Observable.create<Unit> {
                try {
                    ProfessionalInfoActivity.imageInfo = Glide.with(context).load(employmentServerBean.second!!.files[0].url).downloadOnly(workImg.width, workImg.height)
                            .get()
                    it.onNext(Unit)
                } catch (e: Exception) {
                    it.onError(e)
                }
            }.doOnSubscribe {
                mActivity.runOnUiThread {
                    workImg.setImageResource(R.drawable.loading_rotate)
                }
            }.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(object : Subscriber<Unit>() {
                        override fun onCompleted() {
                        }

                        override fun onNext(p0: Unit?) {
                            imgSet()
                            startLoadImg = false
                        }

                        override fun onError(p0: Throwable?) {
                            workImg.setImageResource(R.drawable.error_page)
                            startLoadImg = false
                            XLog.e("professional photo", p0, 100)
                        }

                    })

        }
        updateButtonState()
        if (arguments != null) {
            val needUpdate = arguments!![FieldParams.NEED_UPDATE_REGION]
            if (needUpdate != null && needUpdate as Boolean) {
                updateRegion()
                arguments!!.putBoolean(FieldParams.NEED_UPDATE_REGION, false)
            }
        }
    }

    private fun updateRegion() {
        val regionDatas = HashMap<String, RegionBean.RegionsBean>()
        val level = (mActivity as ProfessionalInfoActivity).getRegionDatas(regionDatas)
        when (level) {
            RegionLevel.province.ordinal -> {
                val province = regionDatas[RegionLevel.province.toString()]
                if (employmentBean.companyProvince?.id != province!!.id) {
                    employmentBean.companyProvince = province
                    /*employmentBean.companyArea = null*/
                    employmentBean.companyDistrict = null
                    employmentBean.companyCity = null
                    employmentBean.companyAddress = null
                }
            }
            RegionLevel.city.ordinal -> {
                val province = regionDatas[RegionLevel.province.toString()]
                val city = regionDatas[RegionLevel.city.toString()]
                if (employmentBean.companyProvince?.id != province!!.id) {
                    employmentBean.companyProvince = province
                    employmentBean.companyCity = city
                    /*employmentBean.companyArea = null*/
                    employmentBean.companyDistrict = null
                    employmentBean.companyAddress = null
                } else if (employmentBean.companyCity?.id != city!!.id) {
                    employmentBean.companyCity = city
                    /*employmentBean.companyArea = null*/
                    employmentBean.companyDistrict = null
                    employmentBean.companyAddress = null
                }
            }
            RegionLevel.district.ordinal -> {
                val province = regionDatas[RegionLevel.province.toString()]
                val city = regionDatas[RegionLevel.city.toString()]
                val district = regionDatas[RegionLevel.district.toString()]
                when {
                    employmentBean.companyProvince?.id != province!!.id -> {
                        employmentBean.companyProvince = province
                        employmentBean.companyCity = city
                        /*employmentBean.companyArea = null*/
                        employmentBean.companyDistrict = district
                        employmentBean.companyAddress = null
                    }
                    employmentBean.companyCity?.id != city!!.id -> {
                        employmentBean.companyCity = city
                        /*employmentBean.companyArea = null*/
                        employmentBean.companyDistrict = district
                        employmentBean.companyAddress = null
                    }
                    employmentBean.companyDistrict?.id != district!!.id -> {
                        /*employmentBean.companyArea = null*/
                        employmentBean.companyDistrict = district
                        employmentBean.companyAddress = null
                    }
                }
            }
            /*RegionLevel.area.ordinal -> {
                val province = regionDatas[RegionLevel.province.toString()]
                val city = regionDatas[RegionLevel.city.toString()]
                val district = regionDatas[RegionLevel.district.toString()]
                val area = regionDatas[RegionLevel.area.toString()]
                when {
                    employmentBean.companyProvince?.id != province!!.id -> {
                        employmentBean.companyProvince = province
                        employmentBean.companyCity = city
                        employmentBean.companyArea = area
                        employmentBean.companyDistrict = district
                        employmentBean.companyAddress = null
                    }
                    employmentBean.companyCity?.id != city!!.id -> {
                        employmentBean.companyCity = city
                        employmentBean.companyArea = area
                        employmentBean.companyDistrict = district
                        employmentBean.companyAddress = null
                    }
                    employmentBean.companyDistrict?.id != district!!.id -> {
                        employmentBean.companyArea = area
                        employmentBean.companyDistrict = district
                        employmentBean.companyAddress = null
                    }
                    employmentBean.companyArea?.id != area!!.id -> {
                        employmentBean.companyArea = area
                        employmentBean.companyAddress = null
                    }
                }
            }*/
            else -> {
                throw IllegalArgumentException("wrong argument of region datas")
            }
        }
        initRegion()
    }

    @SuppressLint("SetTextI18n")
    private fun initRegion() {
        try {
            if (employmentBean.companyProvince != null && /*employmentBean.companyArea != null &&*/ employmentBean.companyCity != null && employmentBean.companyDistrict != null) {
                region.text = employmentBean.companyProvince.name + "-" + employmentBean.companyCity.name + "-" + employmentBean.companyDistrict.name/* + "-" + employmentBean.companyArea.name*/
            } else {
                region.text = null
            }
            companyAddress.text = employmentBean.companyAddress
        } catch (e: Exception) {
            XLog.e("region init exception:", e, 100)
        }
        updateButtonState()
    }

    @SuppressLint("ClickableViewAccessibility")
    private fun findAndInit(view: View) {
        companyAddress = view.find(R.id.id_edittext_job_info_address)
        companyAddress.isEnabled = isEditable
        companyAddress.setItemOnClickListener {
            FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.JOB_FULL_ADDRESS, null)
            val imm: InputMethodManager = activity!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.showSoftInput(companyAddress.editText, 0)
        }

        jobType = view.find(R.id.id_textview_job_info_job_type)
        jobType.apply {
            onClick {
                FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.JOB_OCCUPATION, null)
                setJobType()
            }
            isClickable = isEditable
        }

        companyAge = view.find(R.id.id_textview_job_info_company_age)
        companyAge.apply {
            onClick {
                FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.JOB_YEAR_IN_CURRENT_COMPANY, null)
                ageOP.show()
            }
            isClickable = isEditable
        }

        salaryDate = view.find(R.id.id_textview_job_salary_date)
        salaryDate.apply {
            onClick {
                //                FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.JOB_SALARY_DATE, null)
                salaryDateOP.show()
            }
            isClickable = isEditable
        }

        convenientTime = view.find(R.id.id_textview_job_convenient_time)
        convenientTime.apply {
            onClick {
                //todo 待写
//                FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.JOB_CONVENIENT_TIME, null)
//                setConvenientTime()
            }
            isClickable = isEditable
        }

        salary = view.find(R.id.id_textview_job_info_salary)
        salary.apply {
            onClick {
                FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.JOB_MONTH_SALARY, null)
                setSalary()
            }
            isClickable = isEditable
        }
        companyName = view.find(R.id.id_edittext_job_info_conmany_name)
        companyName.isEnabled = isEditable
        companyName.setItemOnClickListener {
            FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.JOB_COMPANY_NAME, null)
            val imm: InputMethodManager = activity!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.showSoftInput(companyName.editText, 0)
        }

        companyTel = view.find(R.id.id_edittext_job_info_tel)
        companyTel.isEnabled = isEditable
        companyTel.setItemOnClickListener {
            FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.JOB_OFFICE_PHONE_NUMBER, null)
            val imm: InputMethodManager = activity!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.showSoftInput(companyTel.editText, 0)
        }

        jobInfoSubmitButton = view.find(R.id.id_button_job_info_submit)
        jobInfoSubmitButton.apply {
            onClick {
                FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.BTN_EMPLOY_INFO_SUBMIT, null)

                jobInfoSubmit()
            }
            isClickable = isEditable
        }

        jobInfoSubmitButton.setOnTouchListener { v, event ->
            if (!jobInfoSubmitButton.isClickable) {
                val ret = checkUnFillContent()
                ret?.let {
                    XLeoToast.makeText(context, ret, Toast.LENGTH_SHORT).show()
                }
            }
            return@setOnTouchListener false
        }
//        mbdlv = view.find(R.id.bdlv_job_info_telpre)
        region = view.find(R.id.id_textview_job_info_region)
        region.apply {
            onClick {
                FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.JOB_COMPANY_ADDRESS, null)
                getRegion()
            }
            isClickable = isEditable
        }

        example = view.find(R.id.tv_show_id_sample)
        example.onClick {
            FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.BTN_EMPLOY_INFO_PHOTO, null)
            if (!startLoadImg) {
                FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.JOB_EXAMPLE, null)
                activity!!.startActivityForResult(Intent(activity, ExampleActivity::class.java), ProfessionalInfoFragment.EXAMPLE_REQUEST_CODE)
            }
        }

        workImg = view.find(R.id.work_card)
        workImg.apply {
            onClick {
                /*if (!startLoadImg) {
                    val confirmView = LayoutInflater.from(this@ProfessionalInfoFragment.context)
                            .inflate(R.layout.dialog_take_work_photo, null)
                    val confirmDialog = DialogManager.newDialog(this@ProfessionalInfoFragment.context, confirmView, true)
                    confirmView.findViewById<LocalButton>(R.id.btn_ok)
                            .onClick {
                                confirmDialog?.dismiss()
                                TakePhotoActivity.actionStart(mActivity, FileType.EMPLOYMENT_PHOTO)
                            }
                }*/
                FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.JOB_EMPLOYEE_CARD, null)
                openCamera()
            }
            isClickable = isEditable
        }

        changeMarkPosition(view)
    }

    private var stepViewVisible: Boolean = true

    fun setStepViewGone() {
        stepViewVisible = false
    }

    private var stepView: HorizontalStepView? = null
    /**
     * 设置StepView节点状态
     * @param i 当前步骤
     */
    private fun changeMarkPosition(view: View) {
        stepView = view.find(R.id.step_view)

        if (!stepViewVisible) {
            stepView!!.visibility = View.GONE
            return
        }

        val stepsBeanList = java.util.ArrayList<StepBean>()
        val stepBean0 = StepBean("Identification", StepBean.STEP_COMPLETED)
        val stepBean1 = StepBean("Personal Info", StepBean.STEP_COMPLETED)
        val stepBean2 = StepBean("Contact Info", StepBean.STEP_COMPLETED)
        val stepBean3 = StepBean("Job Info", StepBean.STEP_CURRENT)
        stepsBeanList.add(stepBean0)
        stepsBeanList.add(stepBean1)
        stepsBeanList.add(stepBean2)
        stepsBeanList.add(stepBean3)

        stepView!!.setStepViewTexts(stepsBeanList)
    }

    /**
     * 打开相机
     */
    fun openCamera() {
        if (!startLoadImg) {
            TakePhotoActivity.actionStart(mActivity, FileType.EMPLOYMENT_PHOTO)
        }
    }


    fun imgSet() {
        Observable.create<Bitmap> {
            try {
                it.onNext(
                        adjustImg(BitmapFactory.decodeStream(FileInputStream(ProfessionalInfoActivity.imageInfo)), workImg.width, workImg.height)
                )
            } catch (e: Exception) {
                it.onError(e)
            }
        }.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Subscriber<Bitmap>() {
                    override fun onNext(p0: Bitmap?) {
                        if (p0 != null) {
                            workImg.setImageBitmap(p0)
                            workImageReady.updateValue(true)
                        } else {
                            XLog.i("null bitmap", 10)
                        }
                    }

                    override fun onError(p0: Throwable?) {
                        XLog.i("" + p0?.message, 100)
                    }

                    override fun onCompleted() {
                    }

                })

    }

    val workImageReady: DataObserable<Boolean> = DataObserable()
    private fun getRegion() {
        (mActivity as ProfessionalInfoActivity).forwardToNextFragment(null)
    }


    var notFinish: Boolean = false
    var fromSplash: Boolean = false

    override fun initData() {
        if (mActivity.intent.getBooleanExtra(FieldParams.NOT_FINISH_CERTIFY, false)) {
            notFinish = true
        }
        if (mActivity.intent.getBooleanExtra(FieldParams.FROM_SPLASH, false)) {
            fromSplash = true
        }
        if (hasSave) {
            hasSave = false
        } else {
            mPresenter.obtainProfessionData()
        }
        //初始化数据
        ageItem.add("1 to 6 months")
        ageItem.add("6 to 12 months")
        ageItem.add("1 to 3 years")
        ageItem.add("More than 3 years")

        salaryDateItem.add("Bi-monthly(5th and 20th)")
        salaryDateItem.add("Bi-monthly(10th and 25th)")
        salaryDateItem.add("Bi-monthly(15th and 30th)")
        salaryDateItem.add("Weekly(Weekday)")
        salaryDateItem.add("Weekly(Friday)")
        salaryDateItem.add("Weekly(Weekend)")
        salaryDateItem.add("Monthly(15th)")

        //初始化pickerView
        ageOP = OptionsPickerBuilder(context, OnOptionsSelectListener { options1, options2, options3, v ->
            companyAge.text = ageItem[options1]
        })
                .setDividerColor(ContextCompat.getColor(this.context!!, R.color.line_color))//分隔线颜色
                .setContentTextSize(DensityUtils.sp2px(this.context!!, 10))//文字大小
                .setTextColorCenter(ContextCompat.getColor(this.context!!, R.color.theme_grey))//选中颜色大小
                .setTextColorOut(ContextCompat.getColor(this.context!!, R.color.theme_FFBBBBBB))//未选中颜色大小
                .setTextXOffset(0, 0, 0)//去掉3D效果
                .setLineSpacingMultiplier(1.3f)//设置高度
                .setLayoutRes(R.layout.pickerview_custom_options) { v ->
                    val tvSubmit = v.findViewById<View>(R.id.tv_finish) as TextView
                    val tvCancel = v.findViewById<View>(R.id.iv_cancel) as TextView
                    tvSubmit.setOnClickListener {
                        ageOP.returnData()
                        ageOP.dismiss()
                    }
                    tvCancel.setOnClickListener {
                        ageOP.dismiss()
                    }
                }
                .build()
        ageOP.setPicker(ageItem)

        salaryDateOP = OptionsPickerBuilder(context, OnOptionsSelectListener { options1, options2, options3, v ->
            salaryDate.text = salaryDateItem[options1]
        })
                .setDividerColor(ContextCompat.getColor(this.context!!, R.color.line_color))//分隔线颜色
                .setContentTextSize(DensityUtils.sp2px(this.context!!, 10))//文字大小
                .setTextColorCenter(ContextCompat.getColor(this.context!!, R.color.theme_grey))//选中颜色大小
                .setTextColorOut(ContextCompat.getColor(this.context!!, R.color.theme_FFBBBBBB))//未选中颜色大小
                .setTextXOffset(0, 0, 0)//去掉3D效果
                .setLineSpacingMultiplier(1.3f)//设置高度
                .setLayoutRes(R.layout.pickerview_custom_options) { v ->
                    val tvSubmit = v.findViewById<View>(R.id.tv_finish) as TextView
                    val tvCancel = v.findViewById<View>(R.id.iv_cancel) as TextView
                    tvSubmit.setOnClickListener {
                        salaryDateOP.returnData()
                        salaryDateOP.dismiss()
                    }
                    tvCancel.setOnClickListener {
                        salaryDateOP.dismiss()
                    }
                }
                .build()
        salaryDateOP.setPicker(salaryDateItem)
    }

//    private fun initWorkTelPre() {
//        mTelPreStrings = arrayOf("021", "0251")
//        mAdapter = DrapListViewAdapter(mbdlv, R.layout.my_simple_spinner_item, mTelPreStrings)
//        //mAdapter.setDropDownViewResource(R.layout.my_spinner_dropdown_item);
//        //mbdlv.setEmptyView(mTvTel);
//        mbdlv.setAdapter(mAdapter)
//        mbdlv.setSelectedItem(0)
//        mbdlv.isClickable = isEditable
//    }


    // EditText listener
    private fun editTextChangeEvent() {
        val observableCompanyName = RxTextView.textChanges(companyName.editText)
        val observableCompanyAddress = RxTextView.textChanges(companyAddress.editText)
        val observableCompanyTel = RxTextView.textChanges(companyTel.editText)
        val imgObservable = Observable.create<Boolean> {
            workImageReady.addDataChangeListener(object : DataObserable.DataChangeListener<Boolean> {
                override fun onDataChange(t: Boolean?) {
                    it.onNext(t == true)
                }

            })
        }
//        charSequence, charSequence2, charSequence3 -> !TextUtils.isEmpty(charSequence.toString()) || !TextUtils.isEmpty(charSequence2.toString()) || !TextUtils.isEmpty(charSequence3.toString())
        Observable.combineLatest(observableCompanyName, observableCompanyAddress, observableCompanyTel, imgObservable) { _, _, _, _ -> true }.subscribe { updateButtonState() }
    }


    //update submit button
    private fun updateButtonState() {
        if (isCheckedField() && isEditable) {
            jobInfoSubmitButton.isClickable = true
            jobInfoSubmitButton.isSelected = false
        } else {
            jobInfoSubmitButton.isClickable = false
            jobInfoSubmitButton.isSelected = true
        }
    }

    /**
     * Set JobType adapter;

     * @return
     */
    private fun getJobTypeAdapter(): InfoAdapter {
        val jobTypeAdapter = InfoAdapterEnum(context)
        JobStatus.values().forEach {
            jobTypeAdapter.addItem(it, InfoType.JOBTYPE)
        }
        jobTypeAdapter.setOnItemClickListener(object : OnInfoAdapterItemClickListener {
            override fun onItemClick(data: InfoAdapter.InfoItem) {
                onJobTypeSelected(data)
            }

        })
        return jobTypeAdapter
    }

    /**


     * BELOW_2M("below 2,000,000", "小于2,000,000", ""),
     * BETWEEN_2M_4M("between 2,000,000 and 4,000,000", "2,000,000-4,000,000之间", ""),
     * BETWEEN_4M_8M("between 4,000,000 and 8,000,000", "4,000,000-8,000,000之间", ""),
     * BETWEEN_8B_12B("between 8,000,000 and 12,000,000", "8,000,000-12,000,000之间", ""),
     * BETWEEN_12B_20B("between 12,000,000 and 20,000,000", "12,000,000-20,000,000之间", ""),
     * OVER_20B("over 20,000,000", "20,000,000以上", "");
     * @return
     */

    private fun getSalaryAdapter(): InfoAdapter {
        val salaryAdapter = InfoAdapterEnum(context)
        SalaryStatus.values().forEach {
            salaryAdapter.addItem(it, InfoType.SALARY)
        }
        salaryAdapter.setOnItemClickListener(object : OnInfoAdapterItemClickListener {
            override fun onItemClick(data: InfoAdapter.InfoItem) {
                onSalarySelected(data)
            }

        })
        return salaryAdapter
    }

    fun onJobTypeSelected(data: InfoAdapter.InfoItem) {
        //todo 其他选择也一样
        if (data.type == InfoType.JOBTYPE) {
            if (dialogPlus.isShowing) {
                dialogPlus.dismiss()
            }
            jobType.text = data.infoStr
            employmentBean.jobType = data.valueStr
            updateButtonState()
            XLog.d("job type: " + data.infoStr + data.valueStr + employmentBean.jobType, 10)
        }
    }

    fun onSalarySelected(data: InfoAdapter.InfoItem) {
        if (data.type == InfoType.SALARY) {
            if (dialogPlus.isShowing) {
                dialogPlus.dismiss()
            }
            salary.text = data.infoStr
            employmentBean.salary = data.valueStr
            updateButtonState()
        }
    }

    private fun isCheckedField(): Boolean {
        if (TextUtils.isEmpty(jobType.text.toString())) {
            //            XLeoToast.showMessage(getString(R.string.show_input_job_type));
            return false
        }
        /*if (TextUtils.isEmpty(companyAge.text.toString())) {
            //            XLeoToast.showMessage(getString(R.string.show_input_job_type));
            return false
        }
        if (TextUtils.isEmpty(salaryDate.text.toString())) {
            //            XLeoToast.showMessage(getString(R.string.show_input_job_type));
            return false
        }
        if (TextUtils.isEmpty(convenientTime.text.toString())) {
            //            XLeoToast.showMessage(getString(R.string.show_input_job_type));
            return false
        }*/
        if (TextUtils.isEmpty(salary.text?.toString())) {
            //            XLeoToast.showMessage(getString(R.string.show_input_salary));
            return false
        }
        if (!companyName.checkLegal() || TextUtils.getTrimmedLength(companyName.text?.toString()) <= 0) {
            //            XLeoToast.showMessage(getString(R.string.show_input_company_name));
            return false
        }
        if (employmentBean.companyProvince?.name == null) {
            //            XLeoToast.showMessage(getString(R.string.show_input_company_province));
            return false
        }
        if (employmentBean.companyCity?.name == null) {
            //            XLeoToast.showMessage(getString(R.string.show_input_company_city));
            return false
        }
        if (employmentBean.companyDistrict?.name == null) {
            //            XLeoToast.showMessage(getString(R.string.show_input_company_street));
            return false
        }
        /*if (employmentBean.companyArea?.name == null) {
            //            XLeoToast.showMessage(getString(R.string.show_input_company_area));
            return false
        }*/

        if (!companyAddress.checkLegal() || TextUtils.getTrimmedLength(companyAddress.text?.toString()) <= 0) {
            //            XLeoToast.showMessage(getString(R.string.show_input_company_address));
            return false
        }

        if (workImageReady.value != true) {
            return false
        }

        return companyTel.checkLegal()

    }

    private fun setJobType() {
        val jobTypeAdapter = getJobTypeAdapter() as InfoAdapterEnum
        dialogPlus = DialogManager.newListViewDialog(context)
                .setAdapter(jobTypeAdapter)
                .setExpanded(false)
                .setGravity(Gravity.CENTER)
                .create()
        dialogPlus.show()
    }

    private fun setSalary() {
        val salaryAdapter = getSalaryAdapter() as InfoAdapterEnum
        dialogPlus = DialogManager.newListViewDialog(context)
                .setAdapter(salaryAdapter)
                .setExpanded(false)
                .setGravity(Gravity.CENTER)
                .create()
        dialogPlus.show()
    }

    private fun jobInfoSubmit() {
        if (isCheckedField()) {
            //            String position = mbdlv.getSelectedItem();
            //            if (position == null) {
            //                XLeoToast.showMessage(getString(R.string.show_input_areacode));
            //                return;
            //            }
            mActivity.showLoading(resources.getText(R.string.show_uploading).toString())
            employmentBean.companyName = if (companyName.text == null) null else companyName.text.toString().trim()
            employmentBean.companyPhone =
//                    mbdlv.text.toString() +
                    if (companyTel.text != null) companyTel.text.toString().trim() else ""
            employmentBean.companyAddress = if (companyAddress.text == null) null else companyAddress.text.toString().trim()
            mPresenter.uploadJobInfo(ProfessionalInfoActivity.imageInfo, employmentBean)
        } else {
            updateButtonState()
        }
    }

    private fun checkUnFillContent(): String? {
        if (workImageReady.value == null || workImageReady.value == false) {//工牌照
            return getString(R.string.upload_photo)
        }
        if (!jobType.checkLegal()) {//occupation
            return null
        }
        if (TextUtils.isEmpty(companyName.text)) {//公司名
            return null
        } else if (!companyName.checkLegal() && companyName.text?.toString()?.length ?: 0 > 128) {
            return getString(R.string.company_name_too_long)
        }
        if (!salary.checkLegal()) {//薪水
            return null
        }
        if (TextUtils.isEmpty(companyTel.text)) {//公司电话
            return null
        } else if (!companyTel.checkLegal() && companyTel.text?.toString()?.length ?: 0 > 32) {
            return getString(R.string.company_telephone_too_long)
        }
        if (!region.checkLegal()) {//地区
            return null
        }
        if (TextUtils.isEmpty(companyAddress.text)) {//详细地址
            return null
        } else if (!companyAddress.checkLegal() && companyAddress.text?.toString()?.length ?: 0 > 256) {
            return getString(R.string.company_address_too_long)
        }
        return null
    }
}

class ProfessionalInfoPresenterImpl : ProfessionalInfoPresenter, BaseFragmentPresenterImpl() {
    override fun obtainProfessionData() {
        showLoading(null)
        //todo 是否这个api需要调整，EmploymentServerBean是否需要增加字段
        mUserApi.getEmploymentInfo(TokenManager.getInstance().token)
                .zipWith(mUserApi.getJobImg(TokenManager.getInstance().token)) { t1, t2 ->
                    Pair<EmploymentServerBean?, RecordFilesResponse?>(t1, t2)
                }
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Subscriber<Pair<EmploymentServerBean?, RecordFilesResponse?>>() {
                    override fun onCompleted() {

                    }

                    override fun onError(e: Throwable) {

                        if (isAttached) {
                            mView.baseActivity.dismissLoading()
                        }
                        XLog.d("Get EmployeeInfo failed: " + e.message, 10)
                        XLeoToast.showMessage(R.string.show_get_employeeinfo_failed)

                    }

                    override fun onNext(employmentServerBean: Pair<EmploymentServerBean?, RecordFilesResponse?>) {
                        mView.baseActivity.dismissLoading()
                        if (isAttached) {
                            (mView as ProfessionalInfoView).onProfessionDataObtain(employmentServerBean)
                        }
                    }
                })
    }

    override fun uploadJobInfo(img: File?, employmentBean: EmploymentBean) {
//        @Field("companyName") String companyName,
//        @Field("companyProvince") String companyProvince,
//        @Field("companyCity") String companyCity,
//        @Field("companyDistrict") String companyDistrict,
//        @Field("companyArea") String companyArea,
//        @Field("companyAddress") String companyAddress,
//        @Field("companyPhone") String companyPhone,
//        @Field("profession") String profession,
//        @Field("salary") String salary,
        if (ProfessionalInfoActivity.isNewAdd) {
            //todo 增加字段
            mUserApi.submitEmploymentInfo(employmentBean.companyName, employmentBean.companyProvince.name, employmentBean.companyCity.name, employmentBean.companyDistrict.name, /*employmentBean.companyArea.name*/"", employmentBean.companyAddress, employmentBean.companyPhone, employmentBean.jobType, employmentBean.salary, TokenManager.getInstance().token)
                    .zipWith(FileUploadUtil.uploadPhotoFile(FileType.EMPLOYMENT_PHOTO, img!!, TokenManager.getInstance().token)) { t1, t2 ->
                        Pair<android.util.Pair<Call<ResponseBody>, Response<ResponseBody>>, ResponseBody>(t2, t1)
                    }
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(object : Subscriber<Pair<android.util.Pair<Call<ResponseBody>, Response<ResponseBody>>, ResponseBody>>() {
                        override fun onCompleted() {

                        }

                        override fun onError(e: Throwable) {
//                        Toast.makeText(mView.baseActivity, e.message, Toast.LENGTH_SHORT).show()
                            dismissLoading()
                            if (e is HttpException) {
                                try {
                                    val responseErrorBody = Gson().fromJson(e.response()?.errorBody()?.string(), ResponseErrorBody::class.java)
                                    XLeoToast.showMessage("" + responseErrorBody?.message)
                                } catch (e: Throwable) {
                                    XLeoToast.showMessage(R.string.error_occured)
                                }
                            } else {
                                XLeoToast.showMessage(R.string.show_get_region_faild)
                            }
                            XLog.d("submit personall info failed.", 10)
                        }

                        override fun onNext(responseBody: Pair<android.util.Pair<Call<ResponseBody>, Response<ResponseBody>>, ResponseBody>) {
                            XLog.d("Submit success!", 10)
                            if (!isAttached) {
                                return
                            }
                            if ((mView as ProfessionalInfoFragment).firstEdit) {//第一次填写完成
                                RxBus.get().post(EventCollection.FirstFinishCertifyEvent())
                                //跳转到MainActivity
                                val addUserStr = ACache.get(mView.baseActivity).getAsString(FieldParams.ACacheKeys.ACACHE_ADD_USER)
                                MainActivity.startMainActivityAndShowCreditTips(mView.baseActivity, "1" == addUserStr)
                            }
                            ProfessionalInfoActivity.isNewAdd = false
                            FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.BTN_EMPLOY_INFO_SUBMIT_SUCCESS, null)
                            mView.baseActivity.setResult(Activity.RESULT_OK)
                            mView.baseActivity.dismissLoading()
                            mView.baseActivity.finish()
                        }
                    })
        } else {
            //todo 要增加字段
            mUserApi.submitEmploymentInfo(employmentBean.companyName, employmentBean.companyProvince.name, employmentBean.companyCity.name, employmentBean.companyDistrict.name, /*employmentBean.companyArea.name*/"", employmentBean.companyAddress, employmentBean.companyPhone, employmentBean.jobType, employmentBean.salary, TokenManager.getInstance().token)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(object : Subscriber<ResponseBody>() {
                        override fun onCompleted() {

                        }

                        override fun onError(e: Throwable) {
//                        Toast.makeText(mView.baseActivity, e.message, Toast.LENGTH_SHORT).show()
                            XLeoToast.showMessage(R.string.show_get_region_faild)
                            XLog.d("submit personall info failed.", 10)
                            if (!isAttached) {
                                return
                            }
                            mView.baseActivity.dismissLoading()

                        }


                        override fun onNext(responseBody: ResponseBody) {
                            XLog.d("Submit success!", 10)
                            if (!isAttached) {
                                return
                            }
                            mView.baseActivity.setResult(Activity.RESULT_OK)
                            mView.baseActivity.dismissLoading()
                            mView.baseActivity.finish()

                        }
                    })
        }
    }

}

interface ProfessionalInfoView {
    fun onProfessionDataObtain(employmentServerBean: Pair<EmploymentServerBean?, RecordFilesResponse?>)
    fun finish(): Boolean
}

interface ProfessionalInfoPresenter : BaseFragmentPresenter {
    fun uploadJobInfo(img: File?, employmentBean: EmploymentBean)
    fun obtainProfessionData()

}